<?php ini_set("display_errors",true);
error_reporting(E_ALL);
class Goods extends Api\Abstracte\Controller
{
    public $data = [];

    public function __construct()
    {
        parent::__construct();
        $this->load->model('GoodsModel');
        $this->load->model('common_model');
        $this->load->model('mysql_model');
        $this->model = $this->GoodsModel;
		$this->common_model=$this->common_model;
        $this->mysql_model = $this->mysql_model;
        $this->data = [
            "number"=>"GH1537t47",
            "name"=>"商品名称很长",
            "categoryId"=>"16",
            "spec"=>"红色 xxl 冬装",
            "locationId"=>"7",
            "locationName"=>"北京仓库",
            "baseUnitId"=>"2",
            "purPrice"=>"67",
            "salePrice"=>"99",
            "wholesalePrice"=>"77",
            "vipPrice"=>"88",
            "discountRate1"=>"1",
            "discountRate2"=>"8",
            "propertys"=>'[{"locationId":7,"quantity":"58.00","unitCost":8,"amount":464,"batch":"","prodDate":"","safeDays":"","validDate":"","id":0},{"locationId":7,"quantity":"57.00","unitCost":9,"amount":513,"batch":"","prodDate":"","safeDays":"","validDate":"","id":0}]',
            "remark"=>"很贵的衣服",
            "barCode"=>"R3E45r-9",
            "warehouseWarning"=>"1",
            "warehouseWarningSku"=>"0",
            "sonGoods"=>'[{"number":"ghost123456","name":"商品名称ali","spec":"红色 xl 1","unitName":"123/g","qty":"1","salePrice":"48","gid":"1"},{"number":"ghost123456","name":"商品名称ali","spec":"红色 xl 1","unitName":"123/g","qty":"1","salePrice":"48","gid":"1"}]',
	        "warehousePropertys"=>'[{"locationId":7,"locationName":"北京仓库","highQty":100,"lowQty":50},{"locationId":6,"locationName":"1","highQty":100,"lowQty":50}]',
	    ];
    }

    public function index(){
        exit('hello');
    }
	
	
	public function add(){
        $this->input->post(NULL,TRUE);
        $data = $this->data;
		if ($data) {
			$data = $this->validform($data);
			$this->mysql_model->get_count('goods',array('isDelete'=>0,'number'=>$data['number'])) > 0 && str_alert(-1,'商品编号重复');

			$this->db->trans_begin();
            $info = array(
			    'barCode','baseUnitId','unitName','categoryId','categoryName','propertys',
				'discountRate1','discountRate2','highQty','locationId','pinYin',
				'locationName','lowQty','name','number','purPrice','warehouseWarning',
				'remark','salePrice','spec','vipPrice','wholesalePrice','warehousePropertys','sonGoods','dopey'
			);
			$data['dopey']=0;
			if(strlen($data['sonGoods'])>0){
				$sonlist = (array)json_decode($data['sonGoods'],true) ;
				if(count($sonlist)>0){
				    $data['dopey']=1;
				    foreach ($sonlist as $sonkey => $sonrow){
				        if(empty($sonrow['gid']))
				            str_alert(-1,'您所选择的商品ID不存在！请重新选择！');
				        else if($this->mysql_model->get_count('goods',array('isDelete'=>0,'id'=>$sonrow['gid'],'number'=>$sonrow['number'])) <= 0)
				            str_alert(-1,'您所选择的子商品编号“'.$sonrow['number'].'”不存在！请重新选择！');
				    }
				}
			}
			$info = elements($info,$data,NULL);			
			$data['id'] = $this->mysql_model->insert('goods',$info);

			if (strlen($data['propertys'])>0) {                            
				$list = (array)json_decode($data['propertys'],true);
				//exit(print_r($list));
				foreach ($list as $arr=>$row) {
					$v[$arr]['invId']         = $data['id'];
					$v[$arr]['locationId']    = intval($row['locationId']);
					$v[$arr]['qty']           = (float)$row['quantity']; 
					$v[$arr]['price']         = (float)$row['unitCost']; 
					$v[$arr]['amount']        = (float)$row['amount']; 
					$v[$arr]['skuId']         = intval($row['id']);
					$v[$arr]['billDate']      = date('Y-m-d');;
					$v[$arr]['billNo']        = '期初数量';
					$v[$arr]['billType']      = 'INI';
					$v[$arr]['transTypeName'] = '期初数量';
				} 
				if (isset($v)) {
					$this->mysql_model->insert('invoice_info',$v);
				}
			}
			if (strlen($data['warehousePropertys'])>0) {    
			    $list = (array)json_decode($data['warehousePropertys'],true);
				foreach ($list as $arr=>$row) {
					$s[$arr]['invId']         = $data['id'];
					$s[$arr]['locationId']    = intval($row['locationId']);
					$s[$arr]['highQty']       = (float)$row['highQty']; 
					$s[$arr]['lowQty']        = (float)$row['lowQty']; 
				} 
				if (isset($s)) {
					$this->mysql_model->insert('warehouse',$s);
				}     
			}

            if ($this->db->trans_status() === FALSE) {
			    $this->db->trans_rollback();
			    str_alert(-1,'SQL错误回滚');
			} else {
			    $this->db->trans_commit();
				str_alert(200,'success',$data);
			}
		}
		str_alert(-1,'添加失败');
	}

    private function validform($data) {
        $this->load->library('lib_cn2pinyin');
        strlen($data['name']) < 1 && str_alert(-1,'商品名称不能为空');
        strlen($data['number']) < 1 && str_alert(-1,'商品编号不能为空');
        $data['categoryId'] = intval($data['categoryId']);
        $data['baseUnitId'] = intval($data['baseUnitId']);
        $data['categoryId'] < 1 && str_alert(-1,'商品类别不能为空');
        $data['baseUnitId'] < 1 && str_alert(-1,'计量单位不能为空');
        $data['id']        = isset($data['id']) ? intval($data['id']):0;
        $data['lowQty']    = isset($data['lowQty']) ? (float)$data['lowQty'] :0;
        $data['highQty']   = isset($data['highQty']) ? (float)$data['highQty']:0;
        $data['purPrice']  = isset($data['purPrice']) ? (float)$data['purPrice']:0;
        $data['salePrice'] = isset($data['salePrice']) ? (float)$data['salePrice']:0;
        $data['vipPrice']  = isset($data['vipPrice']) ? (float)$data['vipPrice']:0;
        $data['warehouseWarning']  = isset($data['warehouseWarning']) ? intval($data['warehouseWarning']):0;
        $data['discountRate1']  = (float)$data['discountRate1'];
        $data['discountRate2']  = (float)$data['discountRate2'];
        $data['wholesalePrice'] = isset($data['wholesalePrice']) ? (float)$data['wholesalePrice']:0;
        $data['unitName']     = $this->mysql_model->get_row('unit',array('id'=>$data['baseUnitId']),'name');
        $data['categoryName'] = $this->mysql_model->get_row('category',array('id'=>$data['categoryId']),'name');
        $data['pinYin'] = $this->lib_cn2pinyin->encode($data['name']);
        !$data['categoryName'] && str_alert(-1,'商品类别不存在');
        if (strlen($data['propertys'])>0) {
            $list         = (array)json_decode($data['propertys'],true);
            $storage      = $this->mysql_model->get_results('storage',array('disable'=>0));
            $locationId   =  array_column($storage,'id');
            $locationName =  array_column($storage,'name','id');
            foreach ($list as $arr=>$row) {
                !in_array($row['locationId'],$locationId) && str_alert(-1,$locationName[$row['locationId']].'仓库不存在或不可用！');
            }
        }
        $data['warehousePropertys'] = isset($data['warehousePropertys']) ? $data['warehousePropertys'] :'[]';
        $data['warehousePropertys'] = count(json_decode($data['warehousePropertys'],true))>0 ? $data['warehousePropertys'] :'';
        return $data;
    }

    //修改
    public function update(){
        $data = $this->input->post(NULL,TRUE);
        if ($data) {
            $data = $this->validform($data);
            $this->mysql_model->get_count('goods',array('id !='=>$data['id'],'isDelete'=>0,'number'=>$data['number'])) > 0 && str_alert(-1,'商品编号重复');
            $this->db->trans_begin();
            $info = array(
                'barCode','baseUnitId','unitName','categoryId','categoryName','propertys',
                'discountRate1','discountRate2','highQty','locationId','pinYin',
                'locationName','lowQty','name','number','purPrice','warehouseWarning',
                'remark','salePrice','spec','vipPrice','wholesalePrice','warehousePropertys','sonGoods','dopey'
            );
            //add by michen 20170715
            $data['dopey']=0;
            if(strlen($data['sonGoods'])>0){
                $sonlist = (array)json_decode($data['sonGoods'],true) ;
                if(count($sonlist)>0){
                    $data['dopey']=1;
                    foreach ($sonlist as $sonkey => $sonrow){
                        if(empty($sonrow['gid']))
                            str_alert(-1,'您所选择的商品ID不存在！请重新选择！');
                        else if($this->mysql_model->get_count('goods',array('isDelete'=>0,'id'=>$sonrow['gid'],'number'=>$sonrow['number'])) <= 0)
                            str_alert(-1,'您所选择的子商品编号“'.$sonrow['number'].'”不存在！请重新选择！');
                    }
                }
            }
            $info = elements($info, $data,NULL);
            $this->mysql_model->update('goods',$info,array('id'=>$data['id']));
            if (strlen($data['propertys'])>0) {
                $list = (array)json_decode($data['propertys'],true);
                foreach ($list as $arr=>$row) {
                    $v[$arr]['invId']         = $data['id'];
                    $v[$arr]['locationId']    = isset($row['locationId']) ? $row['locationId'] : 0;
                    $v[$arr]['qty']           = isset($row['quantity']) ? $row['quantity']:0;
                    $v[$arr]['price']         = isset($row['unitCost']) ? $row['unitCost']:0;
                    $v[$arr]['amount']        = isset($row['amount']) ? $row['amount']:0;
                    $v[$arr]['skuId']         = isset($row['skuId']) ? $row['skuId']:0;
                    $v[$arr]['billDate']      = date('Y-m-d');
                    $v[$arr]['billNo']        = '期初数量';
                    $v[$arr]['billType']      = 'INI';
                    $v[$arr]['transTypeName'] = '期初数量';
                }
                if (isset($v)) {
                    $this->mysql_model->delete('invoice_info',array('invId'=>$data['id'],'billType'=>'INI'));
                    $this->mysql_model->insert('invoice_info',$v);
                }
            }
            if (strlen($data['warehousePropertys'])>0) {
                $list = (array)json_decode($data['warehousePropertys'],true);
                foreach ($list as $arr=>$row) {
                    $s[$arr]['invId']         = $data['id'];
                    $s[$arr]['locationId']    = isset($row['locationId']) ? $row['locationId'] : 0;
                    $s[$arr]['highQty']       = isset($row['highQty']) ? $row['highQty']:0;
                    $s[$arr]['lowQty']        = isset($row['lowQty']) ? $row['lowQty']:0;
                }
                if (isset($s)) {
                    $this->mysql_model->delete('warehouse',array('invId'=>$data['id']));
                    $this->mysql_model->insert('warehouse',$s);
                }
            }
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                str_alert(-1,'SQL错误回滚');
            } else {
                $this->db->trans_commit();
                //$this->common_model->logs('修改商品:ID='.$data['id'].'名称:'.$data['name']);
                str_alert(200,'success',$this->get_goods_info($data['id']));
            }
        }
        str_alert(-1,'修改失败');
    }

    //删除
    public function delete(){
        $id = str_enhtml($this->input->post('id',TRUE));
        $data = $this->mysql_model->get_results('goods','(id in('.$id.')) and (isDelete=0)');
        if (count($data) > 0) {
            $this->mysql_model->get_count('invoice_info','(invId in('.$id.')) and (isDelete=0) and (billType<>"INI")')>0 && str_alert(-1,'其中有商品发生业务不可删除');
            $sql  = $this->mysql_model->update('goods',array('isDelete'=>1),'(id in('.$id.'))');
            $this->mysql_model->update('invoice_info',array('isDelete'=>1),'(invId in('.$id.'))');

            if ($sql) {
                $name = array_column($data,'name');
                //$this->common_model->logs('删除商品:ID='.$id.' 名称:'.join(',',$name));
                str_alert(200,'success',array('msg'=>'','id'=>'['.$id.']'));
            }
            str_alert(-1,'删除失败');
        }
    }

    private function get_goods_info($id) {
        $data = $this->mysql_model->get_rows('goods',array('id'=>$id,'isDelete'=>0));
        if (count($data)>0) {
            $data['id']            = $id;
            $data['count']         = 0;
            $data['name']          = $data['name'];
            $data['spec']          = $data['spec'];
            $data['number']        = $data['number'];
            $data['salePrice']     = (float)$data['salePrice'];
            $data['purPrice']      = (float)$data['purPrice'];
            $data['wholesalePrice']= (float)$data['wholesalePrice'];
            $data['vipPrice']      = (float)$data['vipPrice'];
            $data['discountRate1'] = (float)$data['discountRate1'];
            $data['discountRate2'] = (float)$data['discountRate2'];
            $data['unitTypeId']    = intval($data['unitTypeId']);
            $data['baseUnitId']    = intval($data['baseUnitId']);
            $data['locationId']    = intval($data['locationId']);
            $data['assistIds']     = '';
            $data['assistName']    = '';
            $data['assistUnit']    = '';
            $data['remark']        = $data['remark'];
            $data['categoryId']    = intval($data['categoryId']);
            $data['unitId']        = intval($data['unitId']);
            $data['length']        = '';
            $data['weight']        = '';
            $data['jianxing']      = '';
            $data['barCode']       = $data['barCode'];
            $data['josl']          = '';
            $data['warehouseWarning']          = intval($data['warehouseWarning']);
            $data['warehouseWarningSku']       = 0;
            $data['skuClassId']          = 0;
            $data['isSerNum']            = 0;
            $data['pinYin']              = $data['pinYin'];
            $data['delete']              = false;
            $data['isWarranty']    = 0;
            $data['safeDays']      = 0;
            $data['advanceDay']    = 0;
            $data['property']      = $data['property'] ? $data['property'] : NULL;
            $propertys = $this->data_model->get_invoice_info('a.isDelete=0 and a.invId='.$id.' and a.billType="INI"');
            foreach ($propertys as $arr=>$row) {
                $v[$arr]['id']            = intval($row['id']);
                $v[$arr]['locationId']    = intval($row['locationId']);
                $v[$arr]['inventoryId']   = intval($row['invId']);
                $v[$arr]['locationName']  = $row['locationName'];
                $v[$arr]['quantity']      = (float)$row['qty'];
                $v[$arr]['unitCost']      = (float)$row['price'];
                $v[$arr]['amount']        = (float)$row['amount'];
                $v[$arr]['skuId']         = intval($row['skuId']);
                $v[$arr]['skuName']       = '';
                $v[$arr]['date']          = $row['billDate'];
                $v[$arr]['tempId']        = 0;
                $v[$arr]['batch']         = '';
                $v[$arr]['invSerNumList'] = '';
            }
            $data['propertys']            = isset($v) ? $v : array();
            if ($data['warehousePropertys']) {
                $warehouse = (array)json_decode($data['warehousePropertys'],true);
                foreach ($warehouse as $arr=>$row) {
                    $s[$arr]['locationId']    = intval($row['locationId']);
                    $s[$arr]['locationName']  = $row['locationName'];
                    $s[$arr]['highQty']       = (float)$row['highQty'];
                    $s[$arr]['lowQty']        = (float)$row['lowQty'];
                }
            }
            $data['warehousePropertys']   = isset($s) ? $s : array();
            if (strlen($data['sonGoods'])>0) {
                $list = (array)json_decode($data['sonGoods'],true);
                foreach ($list as $arr=>$row) {
                    $v[$arr]['number']          = $row['number'];
                    $v[$arr]['name']            = $row['name'];
                    $v[$arr]['spec']            = $row['spec'];
                    $v[$arr]['unitName']        = $row['unitName'];
                    $v[$arr]['qty']             = intval($row['qty']);
                    $v[$arr]['salePrice']       = intval($row['salePrice']);
                    $v[$arr]['gid']             = intval($row['gid']);//add by michen 20170719
                }
            }
            $data['sonGoods']  = isset($v) ? $v : array();

        }
        return $data;
    }

    /**
     * 获取商品列表
     */
    public function getGoodsList(){
        exit(json_encode($this->db->query("select * from ci_goods")->result(),JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    }
	
	public function add_goods($data='asdasdasdasd'){
		if(strlen($data) < 4){
			exit(0);
		}
		if(is_string($data)){
            exit($data);			
		}
		exit(json_encode($data));
	}

}